package com.reader.cms.controller.sys;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.reader.cms.controller.BaseController;
import com.reader.cms.entity.sys.SysOrganization;
import com.reader.cms.mapper.sys.SysOrganizationMapper;
import com.reader.cms.service.sys.ISysOrganizationService;
import com.reader.core.entity.ResultMessageInfo;
import com.reader.core.exception.CustomException;
import com.reader.core.utils.ValidatorUtil;
import com.reader.core.validator.group.AddGroup;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author jiahaikun
 * @description 功能描述
 * @date 2018-08-06
 */
@RestController
@RequestMapping("/api/SysOrganize")
public class SysOrganizationController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(SysOrganizationController.class);

    @Autowired
    public ISysOrganizationService iSysOrganizationService;

    @Autowired
    SysOrganizationMapper sysOrganizationMapper;
//
//    /**
//     * @param currentPage 当前页
//     * @param size        每页记录数
//     * @param param       其它查询条件，根据情况动态添加
//     * @return
//     * @function 分页查询数据
//     */
//    @GetMapping("getPageList")
//    public ResultMessageInfo selectListPage(@RequestParam(value = "currentPage") int currentPage,
//                                                    @RequestParam(value = "size") int size,
//                                                    @RequestParam(value = "param") String param) {
//        ResultMessageInfo resultMessage = null;
//        Page<Map<String, Object>> list = iSysOrganizationService.selectListPage(currentPage, size, "");
//        resultMessage = this.getSuccessResultMessage("MSG_10007", list);
//        return resultMessage;
//    }

    /**
     * 获取组织机构数据集合
     * @param name  机构名称
     * @param code　机构编码
     * @return
     */
    @GetMapping("tree")
    public ResultMessageInfo getOrganizeTree(@RequestParam(value = "name",required = false)String name,
                                                     @RequestParam(value = "code",required = false)String code) {
        ResultMessageInfo resultMessage = null;
        List<SysOrganization> organizations = iSysOrganizationService.getOrganizeTree(name,code);
        return ResultMessageInfo.ofSuccess("查询成功！",organizations);
    }

    /**
     * 获取机构所拥有的角色id集合
     * @param id　机构ＩＤ
     * @return
     */
    @GetMapping("roleIds")
    public ResultMessageInfo getOrganizeRoles(@RequestParam(value = "id") Integer id) {
        ResultMessageInfo resultMessage = null;
        List<Integer> roleIds = iSysOrganizationService.getOrganizeRoles(id);
        return ResultMessageInfo.ofSuccess("成功！",roleIds);
    }


    /**
     * @param sysOrganization 实体对象
     * @return
     * @function 添加新记录
     */
    @PostMapping("insert")
    public ResultMessageInfo insert(@RequestBody SysOrganization sysOrganization) {
        ValidatorUtil.validateEntity(sysOrganization, AddGroup.class);//非空验证
        SysOrganization organization = new SysOrganization();
        organization.setCode(sysOrganization.getCode());
        EntityWrapper<SysOrganization> wrapper = new EntityWrapper<>();
        wrapper.eq("del_flag",0).eq("code",sysOrganization.getCode());
        Integer count = sysOrganizationMapper.selectCount(wrapper);
        if(count != 0){
            return ResultMessageInfo.ofMessage("机构编码已存在！！！");
        }
        ResultMessageInfo resultMessage = null;
        Integer userId = this.getUserId();
        sysOrganization.setDelFlag(0);
        sysOrganization.setInsertUserId(userId);
        sysOrganization.setInsertDt(new Date());
        sysOrganization.setUpdtUserId(userId);
        iSysOrganizationService.insertOrganization(sysOrganization);
        return ResultMessageInfo.ofSuccess("添加成功！");
    }

    /**
     * @param sysOrganization 实体对象
     * @return
     * @function 修改
     */
    @PostMapping("update")
    @Transactional
    @ApiOperation(value = "跟据ID列新记录", notes = "id为必须项")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "要更新对象ID", required = true, dataType = "int", paramType = "path")})
    public ResultMessageInfo update(@RequestBody SysOrganization sysOrganization) {
        ValidatorUtil.validateEntity(sysOrganization, AddGroup.class);//非空验证
        EntityWrapper<SysOrganization> wrapper = new EntityWrapper<>();
        wrapper.eq("del_flag",0).eq("code",
                sysOrganization.getCode()).ne("id",sysOrganization.getId());
        Integer count = sysOrganizationMapper.selectCount(wrapper);
        if(count != 0){
            return  ResultMessageInfo.ofMessage("机构编码已存在！！！");
        }
        sysOrganization.setUpdtDt(new Date());
        sysOrganization.setUpdtUserId(this.getUserId());
        iSysOrganizationService.updateOrganize(sysOrganization);
        return  ResultMessageInfo.ofSuccess("修改成功！");
    }

    /**
     * @param sysOrganization 实体对象
     * @return
     * @function 删除
     */
    @PostMapping("delete")
    @Transactional
    @ApiOperation(value = "跟据ID列新记录", notes = "id为必须项")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "要更新对象ID", required = true, dataType = "int", paramType = "path")})
    public ResultMessageInfo delete(@RequestBody SysOrganization sysOrganization) {
        ValidatorUtil.validateEntity(sysOrganization, AddGroup.class);//非空验证
        sysOrganization.setDelFlag(1);
        sysOrganization.setUpdtDt(new Date());
        sysOrganization.setUpdtUserId(this.getUserId());
        ResultMessageInfo resultMessage = iSysOrganizationService.deleteOrganize(sysOrganization);
        return resultMessage;
    }

    /**
     * @param data 键为ids值为整型数组的json格式
     * @return
     * @function 批量删除对象
     */
    @PostMapping("deleteIds")
    @Transactional
    @ApiOperation(value = "跟据ID删除记录", notes = "键为ids值为整型数组的json格式")
    @ApiImplicitParams({@ApiImplicitParam(name = "ids", value = "id列表", required = true, dataType = "int", paramType = "path")})
    public ResultMessageInfo deleteBatchIds(@RequestBody String data) {
        ResultMessageInfo resultMessage = null;
        List<Long> ids = JSON.parseArray(JSON.parseObject(data).getString("ids"), Long.class);
        boolean resultValue = iSysOrganizationService.deleteBatchIds(ids);
        if (resultValue) {
            resultMessage = ResultMessageInfo.ofSuccess( "删除成功!", resultValue);
        } else {
            return ResultMessageInfo.ofMessage("删除失败!");
        }
        return resultMessage;

    }
}